//
//  AppDelegate.m
//  网络FM
//
//  Created by dengzhicheng on 15/5/21.
//  Copyright (c) 2015年 dengzhicheng.com. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import "MineViewController.h"
#import <AFNetworking.h>
#import "SettingViewController.h"
#import "ViewController2.h"
#import "Player.h"
#import <MediaPlayer/MediaPlayer.h>
#define kAppKey         @"2958669015"
#define kRedirectURI    @"http://www.sina.com"

#import <AVFoundation/AVFoundation.h>
@interface AppDelegate ()

@property(nonatomic ,retain)UIButton *button;
@end

@implementation AppDelegate
- (void)dealloc
{



    [_window release];
    [_sideViewController release];
    [_wbtoken release];
    [_wbCurrentUserID release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:kAppKey];
    
    self.window = [[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds] autorelease];
    [self.window setBackgroundColor:[UIColor whiteColor]];

    [self.window makeKeyAndVisible];
  


    
    // 解决办法    2 个key: @”everLaunched”判断用户以前是否登录,@”firstLaunch” 用来开发者在程序的其他部分判断.
    // 在第一次启动的时候 key @”everLaunched” 不会被赋址的, 并且设置为YES. @”firstLaunch” 被设置为 YES.
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
    }
    else{
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
    }
    
    //
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
      // 这里判断是否第一次
        
        ViewController2 *vie = [[ViewController2 alloc] init];
        [_window setRootViewController:vie];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setRoot) name:@"abc" object:nil];
    }
    else
    {
        
        [self setRoot];
    }

    
    // Override point for customization after application launch.
    return YES;
}

- (void)setRoot
{
    
    // 载入画面
    UIImage *image = [UIImage imageNamed:@"星空FM.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = [[UIScreen mainScreen] bounds];
    [self.window addSubview:imageView];
    [imageView release];
    
    [UIView animateWithDuration:1.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        imageView.alpha = 0.99;
    } completion:^(BOOL finished) {
        // 删除载入画面
        [imageView removeFromSuperview];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"huifu" object:nil];
        
        
        MainViewController *main = [[MainViewController alloc] initWithNibName:nil bundle:nil];
        
        UINavigationController *Nav = [[UINavigationController alloc] initWithRootViewController:main];
        Nav.navigationBar.tintColor = [UIColor blackColor];
        Nav.navigationBar.barTintColor = [UIColor colorWithRed:220 / 255.0 green:220 / 255.0 blue:220 / 255.0 alpha:1.0f];
        
        
        
        MineViewController *mine =[[MineViewController alloc] initWithNibName:nil bundle:nil];
        
        self.sideViewController=[[YRSideViewController alloc]initWithNibName:nil bundle:nil];
        
        self.sideViewController.rootViewController = Nav;
        
        self.sideViewController.leftViewController = mine;
        
        self.sideViewController.leftViewShowWidth= [[UIScreen mainScreen] bounds].size.width / 3 * 2;
        self.sideViewController.needSwipeShowMenu=true;//默认开启的可滑动展示
        //动画效果可以被自己自定义，具体请看api
        [self.window setRootViewController:_sideViewController];
        
        
        [main release];
        [Nav release];
        [mine release];
        
        
        [self createControlView];
        
        
    }];

    
    
}
- (void)createControlView
{
     UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 64, [UIScreen mainScreen].bounds.size.width, 64)];
    [view setBackgroundColor:[UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.8]];
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7, 50, 50)];
    image.layer.cornerRadius = 5;
    image.clipsToBounds =YES;
    [view addSubview:image];
    [image release];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(70, 17, 220, 30)];
    lable.font = [UIFont boldSystemFontOfSize:16];
    lable.textColor = [UIColor lightGrayColor];
    [view addSubview:lable];
    [lable release];
    
    self.button = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 70, 13, 40, 40)];
    [_button setImage:[UIImage imageNamed:@"control_pau.png"] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(buttonStop:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:_button];
    [_button release];
    
    [view setAlpha:0];
    
    [self.window addSubview:view];
    [view release];
}
- (void)buttonStop:(id)sender
{
    Player *play  = [Player playManager];
    if (play.streamer.playbackState ==  MPMoviePlaybackStatePlaying) {
        [play.streamer pause];
        [self.button setImage:[UIImage imageNamed:@"control_pla.png"] forState:UIControlStateNormal];
    }
    else
    {
        [play.streamer play];
        [self.button setImage:[UIImage imageNamed:@"control_pau.png"] forState:UIControlStateNormal];
    }
}
- (void)navButtonClick:(UIButton *)button
{
//    [self.navigationController popViewControllerAnimated:YES];
}

- (void)change:(NSNotification *)not
{
    [self.sideViewController hideSideViewController:NO];
}



- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    
    // 网络请求获得用户信息
    [WBHttpRequest requestWithURL:[NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?access_token=%@&uid=%@", [response.userInfo objectForKey:@"access_token"], [response.userInfo objectForKey:@"uid"]] httpMethod:@"GET" params:nil queue:[NSOperationQueue mainQueue] withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
        
        // 消息中心将字典传给mine视图控制器
        [[NSNotificationCenter defaultCenter] postNotificationName:@"userInformation" object:result];

    }];
    
    // 创建NSUserDefaults对象
    NSUserDefaults *loginState = [NSUserDefaults standardUserDefaults];
    
    // 添加存储内容
    [loginState setObject:@"1" forKey:@"loginState"];
    // 同步存储
    [loginState synchronize];

    
    
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        NSString *message = [NSString stringWithFormat:@"%@: %d\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode, NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil),response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"发送结果"
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
        NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
        if (accessToken)
        {
            self.wbtoken = accessToken;
        }
        NSString* userID = [sendMessageToWeiboResponse.authResponse userID];
        if (userID) {
            self.wbCurrentUserID = userID;
        }
        [alert show];
        [alert release];
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"认证结果"
                                                        message:@"登陆成功"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        
        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
        self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
        [alert show];
        [alert release];
        
    }
    
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WeiboSDK handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [WeiboSDK handleOpenURL:url delegate:self ];
}





- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {

    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
